/*
* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_oh_test/pages/sub_web_page.dart';
import './instance/WebViewInstance.dart';

class WebPage extends StatefulWidget {
  const WebPage({super.key});

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  // 1
  late WebViewController controller;
  String message = "init";
  int paramId = 0;
  var contextRef;

  @override
  void initState() {
    super.initState();
    _initWebView();
  }

  _initWebView() async {
    // 2
    controller = WebViewInstance.controller
      // ..loadRequest(Uri.parse("https://www.baidu.com"))
      // ..loadFlutterAsset("assets/html/index.html")
      // ..loadHtmlString('<a href="/frontend">打开前段页面</a>')
      // ...
      ..setOnJavaScriptAlertDialog((request) async {
        await _showAlert(context, request.message);
      })
      ..setOnJavaScriptConfirmDialog((request) async {
        final bool result = await _showConfirm(context, request.message);
        return result;
      })
      ..setOnJavaScriptTextInputDialog((request) async {
        final String result =
            await _showTextInput(context, request.message, request.defaultText);
        return result;
      })
      ..setNavigationDelegate(NavigationDelegate(
        onUrlChange: (change) {},
      ));
    controller.addJavaScriptChannel(
      "JsObj",
      onMessageReceived: (JavaScriptMessage message) => {
        gotoSubWebPage("https://m.hnair.com")
      },
    );
    controller.loadFlutterAsset("html/index.html");
    print(controller.hashCode);
    print(controller);
  }

  @override
  Widget build(BuildContext context) {
    contextRef = context;
    return Scaffold(
      appBar: AppBar(title: const Text('WebPage')),
      body: Column(children: [
        /*SizedBox(
          height: 50,
          child: Text(message),
        ),
        ElevatedButton(
          onPressed: () => {
            // 执行JavaScript函数
            _onShowUserAgent()
          },
          child: const Text('getUserAgent'),
        ),*/
        Expanded(
          child: WebViewWidget(controller: controller),
        ),
      ]),
    );
  }

  ///跳转子页面
  void gotoSubWebPage(String openUrl) async {
    Navigator.push(
      contextRef,
      MaterialPageRoute(
          builder: (context) => SubWebPage(
            url: openUrl,
          )),
    );
  }

  Future<void> _showAlert(BuildContext context, String message) async {
    return showDialog<void>(
        context: context,
        builder: (BuildContext ctx) {
          return AlertDialog(
            content: Text(message),
            actions: <Widget>[
              TextButton(
                  onPressed: () {
                    Navigator.of(ctx).pop();
                  },
                  child: const Text('OK'))
            ],
          );
        });
  }

  Future<bool> _showConfirm(BuildContext context, String message) async {
    return await showDialog<bool>(
            context: context,
            builder: (BuildContext ctx) {
              return AlertDialog(
                content: Text(message),
                actions: <Widget>[
                  TextButton(
                      onPressed: () {
                        Navigator.of(ctx).pop(false);
                      },
                      child: const Text('Cancel')),
                  TextButton(
                      onPressed: () {
                        Navigator.of(ctx).pop(true);
                      },
                      child: const Text('OK')),
                ],
              );
            }) ??
        false;
  }

  Future<String> _showTextInput(
      BuildContext context, String message, String? defaultText) async {
    return await showDialog<String>(
            context: context,
            builder: (BuildContext ctx) {
              return AlertDialog(
                content: Text(message),
                actions: <Widget>[
                  TextButton(
                      onPressed: () {
                        Navigator.of(ctx).pop('Text test');
                      },
                      child: const Text('Enter')),
                ],
              );
            }) ??
        '';
  }

  Future<void> _onShowUserAgent() {
    // Send a message with the user agent string to the Toaster JavaScript channel we registered
    // with the WebView.
    return controller.runJavaScript(
      'Toaster.postMessage("User Agent: " + navigator.userAgent);',
    );
  }
}
